# Copyright (c) 2024, json_wang and contributors
# For license information, please see license.txt

from erpnext.accounts.report.profit_and_loss_statement.profit_and_loss_statement import get_net_profit_loss
from frappe.utils import cint, cstr, flt, getdate, datetime, get_first_day, get_last_day, formatdate
from frappe.model.document import Document
import frappe
from frappe import _
from erpnext.accounts.utils import FiscalYearError, get_balance_on, get_currency_precision, get_fiscal_year
import datetime
from frappe.utils import getdate
from frappe.utils.data import cstr, nowdate
import pandas as pd
from erpnext.accounts.report.financial_statements import (
	get_columns,
	get_data,
	get_filtered_list_for_consolidated_report,
	get_period_list,
)
from erpnext.accounts.utils import get_balance_on
from frappe.utils import flt


class AC_IncomeStatement(Document):
	@frappe.whitelist()
	def build_report(self):
		doc = frappe.get_doc("AC_IncomeStatement_Config", self.config_version)
		if not doc:
			frappe.throw("没有找到当前公司的报表配置!")
		report_date = datetime.datetime.strptime(self.report_date, "%Y-%m-%d").date()
		from_date =  self.report_date[:4] + "-01-01"
		to_date = get_last_day(report_date).strftime("%Y-%m-%d")	
		last_year_from_date=datetime.date(report_date.year-1, 1, 1).strftime("%Y-%m-%d")
		last_year_to_date=datetime.date(report_date.year-1, 12, 31).strftime("%Y-%m-%d")

		acct_list = []
		for item in doc.items:
			# print(item.acct)
			last_year_total = get_balance_on(company=self.company, 
									account=item.acct, 
									start_date=last_year_from_date,
									date=last_year_to_date,
									ignore_account_permission=True)
			this_year_total = get_balance_on(company=self.company, 
									account=item.acct, 
									start_date=from_date,
									date=to_date,
									ignore_account_permission=True)
			acct_list.append(
				{
					"报表项目": item.rpt_item,
					"科目": item.acct,
					"去年": last_year_total * item.rate,
					"今年": this_year_total * item.rate,
					"序号": item.sort_id,
				}
			)
		# 从字典创建DataFrame
		df = pd.DataFrame.from_dict(acct_list)
		print(df)
		summary = (
			df.groupby("报表项目")
			.agg({"去年": "sum", "今年": "sum", "序号": "max"})
			.reset_index()
			.sort_values(by="序号")
		)
		print(summary)
		# temp = df[["科目","期初","期末"]].rename(columns={'科目': '报表项目'})
		# summary1 = pd.concat([summary,temp]).reset_index(drop=True)
		# print(summary1)
		self.childs = []
		for index, row in summary.iterrows():
			self.append(
				"childs",
				{
					"rpt_item": row["报表项目"],
					"last_year": row["去年"],
					"this_year": row["今年"],
					"sort_id": row["序号"],
				},
			)
		self.refresh_time = datetime.datetime.now()
		self.save(ignore_permissions=True)
